package sanbing.jcpplearning;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;

public class NettyClient {
    public static void main(String[] args) throws Exception {
        // 客户端线程组，用于处理网络事件
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            // 客户端启动器
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group) // 绑定线程组
                    .channel(NioSocketChannel.class) // 指定客户端通道类型
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加 HTTP 编解码器
                            pipeline.addLast(new HttpClientCodec());
                            // 添加 HTTP 报文聚合器
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            // 添加自定义处理器
                            pipeline.addLast(new CustomClientHandler());
                        }
                    });

            System.out.println("Netty 客户端启动...");
            // 连接服务端
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8080).sync();

            // 构造 HTTP 请求
            FullHttpRequest request = new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, 
                    HttpMethod.POST, 
                    "/", 
                    io.netty.buffer.Unpooled.copiedBuffer("hello world", io.netty.util.CharsetUtil.UTF_8)
            );
            request.headers().set(HttpHeaderNames.HOST, "127.0.0.1");
            request.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());

            // 发送 HTTP 请求
            future.channel().writeAndFlush(request);

            // 等待通道关闭
            future.channel().closeFuture().sync();
        } finally {
            // 优雅关闭线程组
            group.shutdownGracefully();
        }
    }

    // 自定义处理器，用于处理服务端响应
    static class CustomClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) {
            // 打印服务端响应内容
            System.out.println("收到服务端响应：");
            System.out.println("状态: " + response.status());
            System.out.println("内容: " + response.content().toString(io.netty.util.CharsetUtil.UTF_8));
        }
    }
}